package com.ruoyi.web.controller.monitor;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.ruoyi.web.otherService.LogService;
import com.sunjob.common.domain.system.SysBusinessLog;
import com.sunjob.common.domain.system.SysExecLog;
import com.sunjob.common.result.Result;
import com.sunjob.common.util.PageHelper;
import io.swagger.models.auth.In;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.service.ISysOperLogService;

/**
 * 操作日志记录
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/monitor/operlog")
public class SysOperlogController extends BaseController {
    private String prefix = "monitor/operlog";

    @Autowired
    private ISysOperLogService operLogService;

    @RequiresPermissions("monitor:operlog:view")
    @GetMapping()
    public String operlog() {
        return prefix + "/operlog";
    }

    @RequiresPermissions("monitor:operlog:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysOperLog operLog) {
        startPage();
        List<SysOperLog> list = operLogService.selectOperLogList(operLog);
        return getDataTable(list);
    }

    @Log(title = "操作日志", businessType = BusinessType.EXPORT)
    @RequiresPermissions("monitor:operlog:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysOperLog operLog) {
        List<SysOperLog> list = operLogService.selectOperLogList(operLog);
        ExcelUtil<SysOperLog> util = new ExcelUtil<SysOperLog>(SysOperLog.class);
        return util.exportExcel(list, "操作日志");
    }

    @Log(title = "操作日志", businessType = BusinessType.DELETE)
    @RequiresPermissions("monitor:operlog:remove")
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(operLogService.deleteOperLogByIds(ids));
    }

    @RequiresPermissions("monitor:operlog:detail")
    @GetMapping("/detail/{operId}")
    public String detail(@PathVariable("operId") Long operId, ModelMap mmap) {
        mmap.put("operLog", operLogService.selectOperLogById(operId));
        return prefix + "/detail";
    }

    @GetMapping("/detailFront/{logId}")
    public String detailFront(@PathVariable("logId") Long logId, ModelMap mp) {
        Result<SysExecLog> sysExecLog = logService.queryExecLogById(logId);
        mp.put("operLog", sysExecLog.getData());
        return prefix + "/detailFront";
    }

    @GetMapping("/detailBusiness/{logId}")
    public String defailBusiness(@PathVariable("logId") Long logId, ModelMap map) {
        Result<Map> sysBusinessLogResult = logService.queryBusinessLogMapById(logId);
        Map data = sysBusinessLogResult.getData();
        map.put("businesslog", data);
        return prefix + "/detailBusiness";
    }

    @Log(title = "操作日志", businessType = BusinessType.CLEAN)
    @RequiresPermissions("monitor:operlog:remove")
    @PostMapping("/clean")
    @ResponseBody
    public AjaxResult clean() {
        operLogService.cleanOperLog();
        return success();
    }


    @Autowired
    LogService logService;

    /**
     * 查询前台操作日志
     *
     * @param sysExecLog
     * @return
     */
    @GetMapping("/queryExecLog")
    @ResponseBody
    public TableDataInfo queryExecLog(SysExecLog sysExecLog, @RequestParam("pageNum") Integer pageNum,@RequestParam("pageSize") Integer paeSize) {
        dateFormat(sysExecLog.getParams());
        Result<List<SysExecLog>> listResult = logService.queryExecLogBy(sysExecLog);
        List<SysExecLog> data = listResult.getData();
        if (data == null) {
            return getDataTable(new ArrayList<>());
        }
        PageHelper<SysExecLog> pageHelper = new PageHelper<>(data);
        List<List<SysExecLog>> pageInfo = pageHelper.getPageInfo(pageNum, paeSize, 1);
        if(pageInfo.size()!=0) return getDataTable(pageInfo.get(0),data.size());
        else return getDataTable(new ArrayList<>(),data.size());
    }

    /**
     * 跳转前台操作页面
     *
     * @return
     */
    @GetMapping("/operlogFront")
    @RequiresPermissions("monitor:operlogFront:view")
    public String toOperLogFront() {
        return prefix + "/operlogFront";
    }

    @GetMapping("/businesslog")
    @RequiresPermissions("monitor:businesslog:view")
    public String toBusinessLog() {
        return prefix + "/businesslog";
    }

    @GetMapping("/queryBusinesslog")
    @ResponseBody
    public TableDataInfo queryBusinesslog(SysBusinessLog sysBusinessLog,@RequestParam("pageNum") Integer pageNum,@RequestParam("pageSize") Integer pageSize) {

        dateFormat(sysBusinessLog.getParams());
        Result<List<Map>> listResult = logService.querySysBusinessLogBy(sysBusinessLog);
        List<Map> data = listResult.getData();
        if (data == null) {
            return getDataTable(new ArrayList<>());
        }
        PageHelper<Map> pageHelper = new PageHelper(data);
        List<List<Map>> pageInfo = pageHelper.getPageInfo(pageNum, pageSize, 1);
        if(pageInfo.size()!=0) return getDataTable(pageInfo.get(0),data.size());
        else return getDataTable(new ArrayList<>(),data.size());
    }

    private void dateFormat(Map<String, Object> map) {
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendPattern("yyyy-MM-dd[['T'HH][:mm][:ss]]")
                .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
                .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                .parseDefaulting(ChronoField.MILLI_OF_SECOND, 0)
                .toFormatter();
        for (String t : map.keySet()) {
            if (!(map.get(t) == null || map.get(t).toString().trim().length() == 0)) {
                LocalDateTime parse = LocalDateTime.parse(map.get(t).toString(), formatter);
                // 转换为时间戳
                map.put(t, parse.toInstant(ZoneOffset.of("+8")).toEpochMilli());
            } else {
                map.put(t, null);
            }
        }
    }
}
